package cn.fenqing168.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * nio 复制文件
 *
 * @author fenqing
 */
public class NioFileChannel3 {

    public static void main(String[] args) {

        try (
                //创建一个文件输入流
                //创建一个文件输出流
                FileInputStream fis = new FileInputStream("./nio/fileChannel3.txt");
                FileOutputStream fos = new FileOutputStream("./nio/fileChannel3.copy.txt")
        ) {
            //从输入流中获取一个channel
            FileChannel inChannel = fis.getChannel();
            //从输出流中获取一个channel
            FileChannel outChannel = fos.getChannel();
            //创建一个byteBuffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //循环读取数据，并写出到输出流对应的channel
            while (inChannel.read(buffer) != -1){
                //将读到数据的缓冲反转
                buffer.flip();
                //将缓冲中的数据写出到outChannel
                outChannel.write(buffer);
                //清空缓冲，准备下一次读取
                buffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
